package com.xyh.web;

import com.xyh.pojo.Comment;
import com.xyh.pojo.User;
import com.xyh.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Value("${comment.avatar}")
    private String avatar;//头像
    /**
     * 获得当前blog的所有评论
     * @param blogId blog的Id
     * @param model model
     * @return blog页面的commentList部分
     */
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.getCommentByBlogId(blogId));
        return "blog::commentList";
    }

    /**
     * 保存评论
     * @param comment 评论
     * @return 回到当前评论的页面
     */
    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user!=null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            comment.setAvatar(avatar);
        }
        commentService.save(comment);
        return "redirect:/comments/"+comment.getBlogId();
    }
    /**
     * 保存留言
     * @param comment 评论
     * @return 回到当前评论的页面
     */
    @PostMapping("/comments/message")
    @ResponseBody
    public int message(Comment comment){
        comment.setBlogId(0L);
        comment.setCreateTime(new Date());
        return commentService.save(comment);
    }
}
